package il.technion.cs236369.webserver;

import java.util.HashMap;

import org.apache.http.protocol.HttpContext;

public class Session implements ISession
{
	private HashMap<String, Object> params = null;

	public Session()
	{
		params = new HashMap<String, Object>();
	}
	
	/**
	 * sets value to be associated with key throughout the session lifetime.
	 * 
	 * @param key
	 * @param value
	 */
	public void SetParameter(String key, Object value)
	{
		params.put(key, value);
	}

	/**
	 *  gets a pre-saved value or null if name not found.
	 *  
	 * @param key
	 * @return value associated with key or null if not found
	 */
	public Object GetParameter(String key)
	{
		return params.get(key);
	}
	
	/**
	 * invalidates the session and frees all data associated with it.
	 */
	public void invalidate()
	{
		params.clear();
	}

	public boolean isEmpty()
	{
		return params.isEmpty();
	}

	/**
	 * Makes sure that the given context and the session contain the same parameters
	 * @param context
	 */
	public void EqualiseWith(HttpContext context)
	{
		String field = (String)context.getAttribute("user");
		if (field != null && GetParameter("user") == null)
		{
			SetParameter("user", field);
		}
		field = (String)context.getAttribute("coors");
		if (field != null)
		{
			SetCoordinates(field);
			context.removeAttribute("coors");
		}
		
		for (String key : params.keySet())
		{
			((HttpContextImpl)context).setAttribute(key, GetParameter(key));
		}
	}

	/**
	 * Adds the given coordinates to the session in a running tally of coors#
	 * @param coors
	 */
	public void SetCoordinates(String coors)
	{
		int i = 0;
		if (GetParameter(coors) != null)
		{
			return;
		}
		
		do
		{
			// if there is no such coors#, add these and quit
			if (GetParameter("coors"+String.valueOf(i)) == null)
			{
				SetParameter("coors"+String.valueOf(i), coors);
				coors = null;
			}
			i += 1;
		} while (coors != null);
	}
	
}
